Hungarian Algorithm


In [2]:
import opengm
import numpy


numObjects = 4
costs = numpy.random.rand(numObjects,numObjects)
print costs


[[ 0.28239879  0.26447532  0.24284484  0.66368517]
 [ 0.49920622  0.16588125  0.49527155  0.22744997]
 [ 0.19698773  0.35439322  0.0827846   0.04164338]
 [ 0.61382719  0.37826025  0.13805748  0.95151257]]

Soft Constraint GM


In [4]:
gm = opengm.gm([numObjects]*numObjects)

unaryIds = gm.addFunctions(costs)
gm.addFactors(unaryIds,numpy.arange(numObjects))

f1To1=opengm.pottsFunction([numObjects,numObjects],10000.0, 0.0)
f1To1Id=gm.addFunction(f1To1)

for x0 in range(numObjects):
    for x1 in range(x0+1,numObjects):
        gm.addFactor(f1To1Id,[x0,x1])

Inference with Lazy Flipper


In [8]:
Inf = opengm.inference.LazyFlipper
param = opengm.InfParam(maxSubgraphSize=1)
inf = Inf(gm=gm,parameter=param)
inf.infer()
arg = inf.arg()
print arg, gm.evaluate(arg)
print len(numpy.unique(arg))


[2 1 3 0] 1.0641966675
4

In [9]:
Inf = opengm.inference.LazyFlipper
param = opengm.InfParam(maxSubgraphSize=2)
inf = Inf(gm=gm,parameter=param)
# use warm start
inf.setStartingPoint(arg)
inf.infer()
arg = inf.arg()
print arg, gm.evaluate(arg)
print len(numpy.unique(arg))


[0 1 3 2] 0.627980907228
4

In [10]:
Inf = opengm.inference.LazyFlipper
param = opengm.InfParam(maxSubgraphSize=3)
inf = Inf(gm=gm,parameter=param)
inf.infer()
# use warm start
inf.setStartingPoint(arg)
arg = inf.arg()
print arg, gm.evaluate(arg)
print len(numpy.unique(arg))


[0 1 3 2] 0.627980907228
4

Hard Constraint GM


In [11]:
gmB = opengm.gm([numObjects]*numObjects)

unaryIds = gmB.addFunctions(costs)
gmB.addFactors(unaryIds,numpy.arange(numObjects))


Out[11]:
3L

Inference with LpCplex


In [12]:
cplexParam = opengm.InfParam(integerConstraint=True)
lpCplex = opengm.inference.LpCplex(gm=gm,parameter=cplexParam)


for x0 in range(numObjects):
    for x1 in range(x0+1,numObjects):
        
        for label in range(numObjects):
            lpVarx0  = lpCplex.lpNodeVariableIndex(x0,label)
            lpVarx1  = lpCplex.lpNodeVariableIndex(x1,label)
            constraintVars  = [lpVarx0,lpVarx1]
            constraintCoeff = [1.0,1.0]
            lowerBound = 0.0
            upperBound = 1.0
            lpCplex.addConstraint(constraintVars,constraintCoeff,lowerBound,upperBound)
            
            
lpCplex.infer()
arg = lpCplex.arg()
print arg, gm.evaluate(arg)
print len(numpy.unique(arg))


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-6c150b576b9d> in <module>()
      1 cplexParam = opengm.InfParam(integerConstraint=True)
----> 2 lpCplex = opengm.inference.LpCplex(gm=gm,parameter=cplexParam)
      3 
      4 
      5 for x0 in range(numObjects):

AttributeError: 'module' object has no attribute 'LpCplex'